<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Poll_lib extends MY_Controller
{
	protected $ci;
	
	public function __construct()
	{
		$this->ci =& get_instance();
		$this->ci->load->library('user_lib');
		$this->ci->load->model('poll_model');
	}
	
	/**
	 * 설문 투표가능여부 검사
	 * @author 박지수
	 * @param int	설문 ID
	 * @param int	사용자 ID
	 * @param float	위도
	 * @param float	경도
	 * @return int	결과 상수 (config/constants.php 참조)
	 */
	function can_user_vote($poll_id, $user_id = NULL, $lat = NULL, $lng = NULL)
	{
		$poll = $this->ci->poll_model->get_poll_common_by_id($poll_id);
		if( ! $poll){
			$expired_poll = $this->ci->poll_model->get_poll_common_by_id($poll_id, TRUE);
			if($expired_poll)
				return POLL_ENDED;
			else
				return POLL_NOT_EXISTS;
		}
		
		$now = time();
		if( strtotime($poll->poll_start) > $now )	return POLL_NOT_STARTED;
		if( strtotime($poll->poll_end) < $now )		return POLL_ENDED;
		if( $poll->daily_start && strtotime($poll->daily_start) > $now )	return POLL_NOT_STARTED_DAILY;
		if( $poll->daily_end && strtotime($poll->daily_end) < $now )		return POLL_ENDED_DAILY;
		
		if( $poll->max_people > 0 && $poll->max_people <= $this->ci->poll_model->count_vote($poll_id, $poll->type))
			return POLL_VOTE_LIMIT_REACHED;
		
		if($poll->login_required)
		{
			$user = $this->ci->user_lib->get_user_by_id($user_id);
			if( ! $user)
				return POLL_LOGIN_REQUIRED;
			
			if( ! $this->ci->poll_model->is_user_matched_to_conditions($poll_id, $user_id))
				return POLL_CONDITION_UNMATCHED;
			
			$latest_vote = $this->ci->poll_model->get_latest_vote_by_user($poll_id, $user_id);
			if($latest_vote && ($poll->type === POLL_TYPE_ONCE || strtotime($latest_vote) > strtotime("today 00:00")))
				return POLL_ALREADY_ANSWERED;
		}
		
		if(strlen($poll->location) > 2 && ( ! $lat || ! $lng || ! $this->ci->poll_model->is_location_matched($poll_id, $lat, $lng) ))
		{
			return POLL_LOCATION_UNMATCHED;
		}
		
		return POLL_OK;
	}
}